import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:stock_check/page/Camera.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:stock_check/widget/InputDialog.dart';
import 'package:stock_check/widget/MyScaffold.dart';
import 'package:stock_check/common/dao/WorksDao.dart';
import 'package:stock_check/widget/CommonsWidget.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/model/assetItemInfo.dart';
import 'package:stock_check/widget/needCheckItemWidget.dart';
import 'package:stock_check/common/utils/NavigatorUtils.dart';
import 'package:stock_check/common/model/checkITDeviceItem.dart';
import 'package:stock_check/common/model/checkInstitutionDetail.dart';
import 'package:stock_check/common/model/checkITDeviceItemDetail.dart';

class NeedCheckDeviceList extends StatefulWidget {
  final CheckITDeviceItem item;
  final String type;

  const NeedCheckDeviceList({Key key, this.item, this.type}) : super(key: key);

  @override
  _NeedCheckDeviceListState createState() => _NeedCheckDeviceListState();
}

class _NeedCheckDeviceListState extends State<NeedCheckDeviceList> {
  CheckITDeviceItemDetail itDetail;
  CheckInstitutionDetail institutionDetail;
  bool noData = false;

  _initAsset() async {
    if (widget.type == 'IT类') {
      CheckITDeviceItemDetail cd = await WorksDao.findITAssetsDetailByRecordID(widget.item.recordId);
      if(cd==null){
        NavigatorUtils.goHome(context);
      }
      setState(() {
        noData = false;
        itDetail = cd;
      });
    }else{
      CheckInstitutionDetail cm = await WorksDao.findInstitutionAssetsDetailByRecordID(widget.item.recordId);
      if(cm == null){
        NavigatorUtils.goHome(context);
      }
      setState(() {
        noData = false;
        institutionDetail = cm;
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initAsset();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return StoreBuilder<StockState>(builder: (context, store) {
      return MyScaffold(
          title: Text('巡检清单'),
          store: store,
          noLeading: true,
          child: Container(
            child: Column(
              children: <Widget>[
                _renderHeader(),
                Divider(height: 0.0),
                _renderList(widget.type),
                noData ? Text('') : _renderFooter()
              ],
            ),
          ));
    });
  }

  Widget _renderHeader() {
    Color accentColor = Theme
        .of(context)
        .primaryColor;
    accentColor =
    accentColor == Color(0xff212121) ? Colors.greenAccent : accentColor;
    return Card(
      margin: EdgeInsets.zero,
      elevation: 1.0,
      shape: RoundedRectangleBorder(),
      child: ListTile(
        leading: Row(
          children: <Widget>[
            Icon(
              Icons.assignment,
              color: accentColor,
            ),
            Text(
              '  ${widget.item.startTimeStr + '--' + widget.item.planName}',
              style: TextStyle(fontSize: 18.0, color: accentColor),
            ),
          ],
        ),
      ),
    );
  }

  Widget _renderList(String type) {
    if (type == 'IT类') {
      if (itDetail != null && itDetail.assetsList.length > 0) {
        return Expanded(
          child: ListView.builder(
              itemBuilder: (context, index) {
                return NeedCheckItemWidget(item: itDetail.assetsList[index],
                  type: widget.type,
                  detail: itDetail,
                  context: context,);
              },
              itemCount: itDetail.assetsList.length),
        );
      } else {
        noData = true;
        return CommonsWidget.getNullData();
      }
    } else {
      if (institutionDetail != null &&
          institutionDetail.assetsList.length > 0) {
        return Expanded(
          child: ListView.builder(
              itemBuilder: (context, index) {
                return NeedCheckItemWidget(item: institutionDetail.assetsList[index],
                  type: widget.type,
                  detail: institutionDetail,
                  context: context,);
              },
              itemCount: institutionDetail.assetsList.length),
        );
      } else {
        noData = true;
        return Expanded(child:CommonsWidget.getNullData());
      }
    }
  }

  Widget getStatus(String content) {
    if (content.isNotEmpty) {
      return Text(
        '已巡检',
        style: TextStyle(color: Colors.blue),
      );
    } else {
      return Text(
        '未巡检',
        style: TextStyle(color: Colors.red),
      );
    }
  }

  bool _haveCheck(List<AssetItemInfo> item){
    for(int i=0;i<item.length;i++){
      if(item[i].status==0){
        return false;
      }
    }
    return true;
  }

  void _checkAndUpload() async{
    if(widget.type == 'IT类'){
      for(int i=0;i<itDetail.assetsList.length;i++){
        if(!_haveCheck(itDetail.assetsList[i].itemList)){
          Fluttertoast.showToast(msg: '无法上传,还有资产未巡检!',gravity: ToastGravity.CENTER);
          return;
        }
      }
      String content = await showDialog<String>(
          context: context, //BuildContext对象
          barrierDismissible: false,
          builder:(context){
            return InputDialog();
          }
      );
      if(content!=null){
        itDetail.content = content;
        try{
          bool res = await WorksDao.submitITAssetDetail(itDetail);
          if(res==true){
            //删除数据
            await WorksDao.deleteITAssetDetailByRecordID(context,itDetail);
            Navigator.pop(context);
          }else{
            setState(() {
              itDetail.content = null;
            });
          }
        }catch(e){
          setState(() {
            itDetail.content = null;
          });
        }
      }
    }else{
      for(int i=0;i<institutionDetail.assetsList.length;i++){
        if(!_haveCheck(institutionDetail.assetsList[i].itemList)){
          Fluttertoast.showToast(msg: '无法上传,还有资产未巡检!',gravity: ToastGravity.CENTER);
          return;
        }
      }
      String content = await showDialog<String>(
          context: context, //BuildContext对象
          barrierDismissible: false,
          builder:(context){
            return InputDialog();
          }
      );
      if(content!=null){
        institutionDetail.content = content;
        try{
          bool res = await WorksDao.submitInstitutionAssetDetail(institutionDetail);
          if(res==true){
            //删除数据
            await WorksDao.deleteInstitutionsDetailByRecordID(context,institutionDetail);
            Navigator.pop(context);
          }else{
            setState(() {
              institutionDetail.content = null;
            });
          }
        }catch(e){
          setState(() {
            institutionDetail.content = null;
          });
        }
      }
    }
  }

  Widget _renderFooter() {
    return Container(
      height: 100.0,
      width: double.infinity,
      alignment: Alignment.center,
      padding: EdgeInsets.all(10.0),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(
            flex: 8,
            child: OutlineButton(
              padding: EdgeInsets.all(10.0),
              onPressed: () {
                _checkAndUpload();
              },
              borderSide: BorderSide(
                  color: Colors.blue,
                  width: 3.0
              ),
//              shape: RoundedRectangleBorder(
//                  borderRadius: BorderRadius.only(
//                      topLeft: Radius.circular(200.0),
//                      bottomLeft: Radius.circular(200.0)
//                  )
//              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Icon(Icons.cloud_upload, color: Colors.blue),
                  Text(
                    ' 上传结果',
                    style: TextStyle(color: Colors.blue,fontWeight: FontWeight.bold),
                  )
                ],
              ),
            ),
          ),
          Padding(padding: EdgeInsets.all(4.0)),
          Expanded(
            flex: 8,
            child: OutlineButton(
              padding: EdgeInsets.all(10.0),
              onPressed: () {
                Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (context) =>
                            QRViewScan(item: widget.type == 'IT类'
                                ? itDetail
                                : institutionDetail, type: widget.type,)));
              },
              borderSide: BorderSide(
                  color:Colors.blue,
                  width: 3.0
              ),
//              shape: RoundedRectangleBorder(
//                borderRadius: BorderRadius.only(
//                  topRight: Radius.circular(20.0),
//                  bottomRight: Radius.circular(20.0)
//                )
//              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Icon(
                    Icons.camera,
                    color: Colors.blue
                  ),
                  Text(
                    ' 扫描二维码巡检',
                    style: TextStyle(color: Colors.blue,fontWeight: FontWeight.bold),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}